
class Message {
  contextMenus?:ContextMenus
  constructor(contextMenus:ContextMenus) {
    this.init();
    this.contextMenus = contextMenus;
  }

  init() {
    this.listenToPort();
  }

  listenToPort() {
    chrome.runtime.onConnect.addListener((port) => {
      console.log("[BG] dev port 收到消息:", port);
      this.contextMenus?.connectPort(port);
    })
  }
}

class ContextMenus {
  port?:chrome.runtime.Port

  constructor() { 
    this.init();
  }

  init() {
    this.generateContextMenus();
    this.listenContextMenuClick();
  }

  connectPort(port:chrome.runtime.Port) {
    this.port = port;
  }

  /**
   * @description: This function is used to generate the context menus
   * @returns: void
   */
  generateContextMenus() {
    chrome.contextMenus.removeAll(() => {
      try {
        chrome.contextMenus.create({
          id: 'ias',
          title: 'IAS',
          contexts: ['all'],
        });
  
        this.createChatAIContextMenu();
        this.createTemplateStoreContextMenu();
        this.createDevToolsContextMenu();
      } catch (error) {
        console.error('Error creating context menu:', error);
      }
    });
  }

  createChatAIContextMenu() {
    chrome.contextMenus.create({
      id: 'ias_chat',
      title: '开始对话',
      parentId: 'ias',
      contexts: ['all'],
    });
  }

  createTemplateStoreContextMenu() {
    chrome.contextMenus.create({
      id: 'ias_template_store',
      title: '模板商城',
      parentId: 'ias',
      contexts: ['all'],
    });
  }

  createDevToolsContextMenu() {
    chrome.contextMenus.create({
      id: 'ias_dev_tools',
      title: '开发工具',
      parentId: 'ias',
      contexts: ['all'],
    });
  }

  listenContextMenuClick() {
    chrome.contextMenus.onClicked.addListener((info, tab) => {
      // open devtools page
      if (info.menuItemId === 'ias_dev_tools') {
        if(!tab) {
          return;
        }

        this.port?.postMessage({
          action:'openDevTools',
          data: {
            tabId: tab.id
          }
        })
      }

      // open store
      if (info.menuItemId === 'ias_template_store') {
        if(!tab?.id) {
          return;
        }

        chrome.sidePanel.open({
          windowId: tab.windowId,
        })
      }

      return true
    })
  }
}

const contextMenus = new ContextMenus();

new Message(contextMenus);

